package com.linkage.jz.bankruptcy.fragment.Project;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Project.ApplyProNoticeActivity;
import com.linkage.jz.bankruptcy.activity.Project.CreateProjectDetailThreeActivity;
import com.linkage.jz.bankruptcy.activity.Project.ProDetailActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.CreateZQOneProjectActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.EditZQUserBaseInfoActivity;
import com.linkage.jz.bankruptcy.adapter.MyProListViewAdapter;
import com.linkage.jz.bankruptcy.adapter.NoticeRecyclerViewAdapter;
import com.linkage.jz.bankruptcy.adapter.ProjectBaseAdapter;
import com.linkage.jz.bankruptcy.adapter.PublicProListViewAdapter;
import com.linkage.jz.bankruptcy.bean.MyProInfo;
import com.linkage.jz.bankruptcy.bean.NoticeInfo;
import com.linkage.jz.bankruptcy.bean.ZQUserDetailBaseInfo;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.utils.Utils;
import com.linkage.jz.bankruptcy.widget.Divider;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.activity.register.RegisterActivity;
import com.linkage.seapeak.base.BaseFragment;
import com.seapeak.recyclebundle.AYSwipeRecyclerView;
import com.seapeak.recyclebundle.BaseRecyclerAdapter;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildLongClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemLongClickListener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/7/30.
 */

public class PublicProFragment extends BaseFragment implements AYSwipeRecyclerView.OnRefreshLoadListener {

    //显示信息
    //    private static final String TAG = RecyclerViewDemoActivity.class.getSimpleName();
    private ProjectBaseAdapter mAdapter;
    private List<MyProInfo> mData;
    private View ll_nodata;
    private AYSwipeRecyclerView mDataRv;

    int page = 1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pro_publicpro, container, false);
        mDataRv = (AYSwipeRecyclerView) view.findViewById(R.id.rv_recyclerview_data);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initRecyclerView(view);
    }

    @Override
    public void onResume() {
        super.onResume();
        loadFirst();
    }

    private  PublicNoticeDialog noticeDialog;

    private void initRecyclerView(View view) {
        ll_nodata = LayoutInflater.from(getActivity()).inflate(R.layout.empty_pro_publicpro, null);
        mData = new ArrayList<MyProInfo>();
        mAdapter = new ProjectBaseAdapter(getActivity(), mData, ProjectBaseAdapter.PROJECT_PUBLIC);
        mDataRv.setEmptyView(ll_nodata);
        mDataRv.setShowEmpty(true);
        mDataRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (RecyclerView.SCROLL_STATE_DRAGGING == newState) {
                    mAdapter.closeOpenedSwipeItemLayoutWithAnim();
                }
            }
        });
        mDataRv.setOnRefreshLoadLister(this);
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position, RecyclerView.ViewHolder viewHolder) {
                MyProInfo model = mData.get(position);

                BankruptcyApp.mphone = model.getContactPhone();
                BankruptcyApp.mUserid =model.getSendSysUserId();
                BankruptcyApp.mUsername = model.getContacts();
                if (v.getId() == R.id.bt_item_bt1)  {

                    if(model.getAuth().getAllowJoin()) {
                        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
                        if ("".equalsIgnoreCase(userToken)) {
                            noticeDialog = new PublicNoticeDialog(getActivity(), new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    switch (view.getId()) {
                                        case R.id.ll_close:
                                            noticeDialog.dismiss();
                                            break;

                                        case R.id.btn_chancel_notice:
                                            noticeDialog.dismiss();

                                            break;

                                        case R.id.btn_save_notice:
                                            RegisterActivity.start(getActivity());
                                            noticeDialog.dismiss();
                                            break;

                                    }

                                }
                            }, 1, "提示", "操作此功能，需要请您先注册/登录",
                                    "取消", "确认");
                            noticeDialog.show();
                            return;
                        } else {
                            ApplyProNoticeActivity.start(getActivity(), model.getId(), model.getCreditorId(),
                                    model.getManagerId(), "管理人", model.getContactPhone());
                        }
                    }
                    if (model.getProjectColumnList().getFillingIn()) {
                        ZQUserDetailBaseInfo info = new ZQUserDetailBaseInfo();
                        info.setBankruptcyProjectId(model.getId());
                        info.setId(model.getCreditorId());
                        CreateZQOneProjectActivity.start(getActivity(), info,model.getSysAddressId(), model.getContacts(),model.getContactPhone());
                        return;
                    }

                    if (model.getProjectColumnList().getContinueFillingIn()) {
                        getTempData(model.getCreditorId(),model.getId());
                        return;
                    }
                } else {
                    try {

                        if (model != null) {
                            Intent intent = new Intent(getActivity(), ProDetailActivity.class);
                            intent.putExtra("info", new Gson().toJson(model));
                            getActivity().startActivity(intent);
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });

        mDataRv.setAdapter(mAdapter);
    }

    private long lastclick_getList;
    public void getData() {
        if (BankruptcyApp.tokeninfo == null) {
            return;
        }
        if (System.currentTimeMillis() - lastclick_getList <= 1000) {
            return;
        }
        lastclick_getList = System.currentTimeMillis();

        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        OkHttpClient okHttpClient = new OkHttpClient();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.appid)
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("userToken", userToken)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("pageNumber", page + "")
                .add("pageSize", "20")
                .add("keywords", "")
                .build();

        String url = Consts.WEBURL_GETPUBLICPRO;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String str = response.body().string();
                if (getActivity() != null) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                JSONObject object = new JSONObject(str);
                                JSONObject jsondata = object.getJSONObject("data");
                                int totalCount = jsondata.optInt("totalCount");

                                MyProInfo[] array = new Gson().fromJson(jsondata.optString("list"), MyProInfo[].class);
                                List<MyProInfo> list = Arrays.asList(array);
                                if (page == 1)
                                    mData.clear();
                                page++;
                                for (int i = 0; i < list.size(); i++) {
                                    MyProInfo info = list.get(i);
                                    mData.add(info);
                                }
                                mDataRv.onFinishRequest(false, totalCount > mData.size());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }

            }
        });
    }

    @Override
    public void loadFirst() {
        page = 1;
        getData();
    }

    @Override
    public void loadNext() {
        getData();
    }

    public void  getTempData
            (final String creditorId,final String proid)
    {
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        Network.getAPIService()
                .fetchCreditorInfoTemp(userToken, creditorId,proid,"1")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        try {
                            int code = json.get("code").getAsInt();

                            if (code != 0) {
                                ToastUtil.showShort("请求数据错误");
                                return;
                            }

                            JsonObject data = json.getAsJsonObject("data");
                            if(data == null ) {
                                ZQUserDetailBaseInfo info = new ZQUserDetailBaseInfo();
                                info.setId(creditorId);
                                info.setBankruptcyProjectId(proid);

                                EditZQUserBaseInfoActivity.start(getActivity(), info, 1, 0);
                            }else {

                                ZQUserDetailBaseInfo info = new Gson().fromJson(json.getAsJsonObject("data"), ZQUserDetailBaseInfo.class);
                                info.setId(info.getCreditorId());
                                EditZQUserBaseInfoActivity.start(getActivity(), info, 1, 1);
                            }

//                            info.setBankruptcyProjectId(mProID);


                        }catch (Exception ex) {
                            ex.printStackTrace();
                            ZQUserDetailBaseInfo info = new ZQUserDetailBaseInfo();
                            info.setId(creditorId);
                            info.setBankruptcyProjectId(proid);
                            EditZQUserBaseInfoActivity.start(getActivity(), info, 1, 0);

                        }
                    }

                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        mDataRv.onFinishRequest(true, false);
                    }
                });
    }
}
